<!-- 搜索结果页面 -->
<template>
  <div class="search-container">
    <!-- 页面标题和搜索框区域 -->
    <div class="search-hero">
      <h1 class="search-title">查找您理想的民宿</h1>
      
      <!-- 搜索框区域 -->
      <div class="search-bar-wrapper">
        <el-input
          v-model="localSearchKeyword"
          placeholder="输入关键词搜索理想民宿..."
          class="search-input"
          clearable
          prefix-icon="el-icon-search"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button type="primary" @click="handleSearch">
              搜索
            </el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 当前搜索信息 -->
      <div class="search-info" v-if="searchKeyword || (searchDateRange.startDate && searchDateRange.endDate)">
        <span class="info-label">当前搜索: </span>
        <template v-if="searchKeyword">
          <span class="search-tag">
            <i class="el-icon-search"></i> {{ searchKeyword }}
          </span>
        </template>
        <template v-if="searchDateRange.startDate && searchDateRange.endDate">
          <span class="search-tag">
            <i class="el-icon-date"></i> {{ searchDateRange.startDate }} 至 {{ searchDateRange.endDate }}
          </span>
        </template>
      </div>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-header">
        <i class="el-icon-filter"></i>
        <span>筛选条件</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="filter-item">
            <label class="filter-label">地区</label>
            <el-select v-model="filters.area" placeholder="选择地区" clearable style="width: 100%">
              <el-option
                v-for="item in areaOptions"
                :key="item.name"
                :label="item.label"
                :value="item.name"
              />
            </el-select>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="filter-item">
            <label class="filter-label">民宿类型</label>
            <el-select v-model="filters.type" placeholder="选择类型" clearable style="width: 100%">
              <el-option
                v-for="item in typeOptions"
                :key="item.name"
                :label="item.label"
                :value="item.name"
              />
            </el-select>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="filter-item">
            <label class="filter-label">价格区间</label>
            <el-select v-model="filters.price" placeholder="选择价格" clearable style="width: 100%">
              <el-option
                v-for="item in priceOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="filter-item">
            <label class="filter-label">容纳人数</label>
            <el-select v-model="filters.capacity" placeholder="选择容纳人数" clearable style="width: 100%">
              <el-option
                v-for="item in capacityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="filter-buttons">
            <el-button type="primary" @click="applyFilters" class="filter-button">
              <i class="el-icon-check"></i> 应用筛选
            </el-button>
            <el-button @click="resetFilters" class="filter-button">
              <i class="el-icon-refresh"></i> 重置
            </el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    
    <!-- 搜索结果列表 -->
    <div class="search-results" v-loading="loading">
      
      <template v-if="homestays.length > 0">
        <el-row :gutter="24">
          <el-col
            v-for="homestay in homestays"
            :key="homestay.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
          >
            <el-card class="homestay-card" shadow="hover" @click="navigateToDetail(homestay.id)">
              <div class="homestay-image">
                <img :src="homestay.images[0]" :alt="homestay.name" />
                <div class="homestay-price">¥{{ homestay.price }}<span class="price-unit">/晚</span></div>
              </div>
              <div class="homestay-info">
                <div class="homestay-type-badge">{{ homestay.type }}</div>
                <h3 class="homestay-name">{{ homestay.name }}</h3>
                <p class="homestay-area">
                  <i class="el-icon-location"></i> {{ homestay.area }}
                </p>
                <div class="homestay-rating">
                  <el-rate
                    v-model="homestay.rating"
                    disabled
                    text-color="#ff9900"
                    score-template="{value}"
                  />
                  <span class="review-count">浏览量 {{ homestay.viewCount }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 分页 -->
        <div class="pagination-section" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[8, 12, 16, 24]"
            :total="total"
            background
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange">
          </el-pagination>
        </div>
      </template>
      
      <!-- 无结果时显示 -->
      <el-empty 
        v-else 
        description="没有找到符合条件的民宿"
        :image-size="200"
      >
        <el-button type="primary" @click="goToHomePage">返回首页</el-button>
        <el-button @click="resetFilters">清除筛选条件</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, defineComponent } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from '@/utils/request';

// 定义组件名称以解决ESLint的多词命名要求
defineComponent({
  name: 'SearchPage'
});

// 路由
const router = useRouter();
const route = useRoute();

// 搜索参数
const searchKeyword = ref('');
const localSearchKeyword = ref(''); // 本地搜索关键词
const searchDateRange = reactive({
  startDate: '',
  endDate: ''
});

// 排序选项
const sortOption = ref('recommended');

// 筛选条件
const filters = ref({
  area: '',
  type: '',
  price: '',
  capacity: ''
});

// 分页
const currentPage = ref(1);
const pageSize = ref(8);
const total = ref(0);

// 搜索结果
const homestays = ref([]);
const loading = ref(false);
const typeOptions = ref([])
const areaOptions = ref([])



// 价格区间选项
const priceOptions = [
  { value: '0-300', label: '¥300以下' },
  { value: '300-500', label: '¥300-500' },
  { value: '500-800', label: '¥500-800' },
  { value: '800-1000', label: '¥800-1000' },
  { value: '1000+', label: '¥1000以上' }
];

// 容纳人数选项
const capacityOptions = [
  { value: '1', label: '1人' },
  { value: '2', label: '2人' },
  { value: '4', label: '4人' },
  { value: '6', label: '6人' },
  { value: '8', label: '8人' },
  { value: '10', label: '10人' }
];

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await request.get('/homestayCategory/list')
    
    if (res.data.code === '200') {
      typeOptions.value = res.data.data || []
      console.error('获取分类列表成功:', typeOptions.value)
    } else {
      console.error('获取分类列表失败:', res.data.msg)

    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
  }
}


//地区分类
const fetchCategoriesReing = async () => {
  try {
    const res = await request.get('/homestayRegin/list')
    
    if (res.data.code === '200') {
      areaOptions.value = res.data.data || []
    } else {
      console.error('获取分类列表失败:', res.data.msg)

    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
  }
}
// 从URL参数中获取搜索条件
const getSearchParams = () => {
  const { keyword, startDate, endDate } = route.query;
  
  if (keyword) {
    searchKeyword.value = keyword;
    localSearchKeyword.value = keyword; // 同步设置本地搜索关键词
  }
  
  if (startDate && endDate) {
    searchDateRange.startDate = startDate;
    searchDateRange.endDate = endDate;
  }
};

// 处理搜索操作
const handleSearch = () => {
  searchKeyword.value = localSearchKeyword.value;
  
  // 更新URL参数
  const query = { ...route.query, keyword: localSearchKeyword.value };
  router.push({ path: route.path, query });
  
  // 重置为第一页并搜索
  currentPage.value = 1;
  searchHomestays();
};

// 搜索民宿
const searchHomestays = async () => {
  loading.value = true;
  
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    };
    
    // 添加搜索关键词
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
    }
    
    // 添加日期范围
    if (searchDateRange.startDate && searchDateRange.endDate) {
      params.startDate = searchDateRange.startDate;
      params.endDate = searchDateRange.endDate;
    }
    
    // 添加筛选条件
    if (filters.value.area) {
      params.area = filters.value.area;
    }
    if (filters.value.type) {
      params.type = filters.value.type;
    }
    if (filters.value.price) {
      const [min, max] = filters.value.price.split('-');
      params.minPrice = min;
      if (max !== '+') {
        params.maxPrice = max;
      }
    }
    if (filters.value.capacity) {
      params.capacity = filters.value.capacity;
    }
    
    // 添加排序选项
    if (sortOption.value !== 'recommended') {
      params.sort = sortOption.value;
    }
    
    // 发送请求
    const res = await request.get('/homestays/page', { params });
    homestays.value = res.data.data.records || [];
    total.value = res.total || homestays.value.length;
    
    // 确保每个民宿的images属性是数组
    homestays.value.forEach(homestay => {
      if (!Array.isArray(homestay.images)) {
        if (homestay.img) {
          homestay.images = [homestay.img];
        } else if (typeof homestay.images === 'string') {
          try {
            homestay.images = JSON.parse(homestay.images);
          } catch (e) {
            homestay.images = [homestay.images];
          }
        } else {
          homestay.images = [];
        }
      }
    });
  } catch (error) {
    console.error('搜索民宿失败:', error);
    // 使用模拟数据
    fallbackToMockData();
  } finally {
    loading.value = false;
  }
};

// 监听排序选项变化
watch(sortOption, () => {
  searchHomestays();
});

// 使用模拟数据
const fallbackToMockData = async () => {
  try {
    const { homestayList } = await import('../mock');
    let filteredList = [...homestayList];
    
    // 关键字过滤
    if (searchKeyword.value) {
      filteredList = filteredList.filter(item => 
        item.name.includes(searchKeyword.value) || 
        item.area.includes(searchKeyword.value) ||
        (item.description && item.description.includes(searchKeyword.value))
      );
    }
    
    // 筛选条件过滤
    if (filters.value.area) {
      filteredList = filteredList.filter(item => item.area === filters.value.area);
    }
    
    if (filters.value.type) {
      filteredList = filteredList.filter(item => item.type === filters.value.type);
    }
    
    if (filters.value.price) {
      const [min, max] = filters.value.price.split('-');
      if (max === '+') {
        filteredList = filteredList.filter(item => item.price >= parseInt(min));
      } else {
        filteredList = filteredList.filter(item => 
          item.price >= parseInt(min) && item.price <= parseInt(max)
        );
      }
    }
    
    if (filters.value.capacity) {
      filteredList = filteredList.filter(item => item.capacity == parseInt(filters.value.capacity));
    }
    
    homestays.value = filteredList;
    total.value = homestays.value.length;
  } catch (error) {
    console.error('加载模拟数据失败:', error);
    homestays.value = [];
    total.value = 0;
  }
};

// 应用筛选
const applyFilters = () => {
  currentPage.value = 1;
  searchHomestays();
};

// 重置筛选
const resetFilters = () => {
  filters.value = {
    area: '',
    type: '',
    price: '',
    capacity: ''
  };
  searchKeyword.value = '';
  localSearchKeyword.value = '';
  
  // 更新URL参数，移除关键词参数
  const query = { ...route.query };
  delete query.keyword;
  router.push({ path: route.path, query });
  
  currentPage.value = 1;
  searchHomestays();
};

// 页码变化处理
const handlePageChange = (page) => {
  currentPage.value = page;
  searchHomestays();
  window.scrollTo(0, 0);
};

// 每页大小变化处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  searchHomestays();
  window.scrollTo(0, 0);
};

// 跳转到详情页
const navigateToDetail = (id) => {
  router.push(`/homestay/${id}`);
};

// 返回首页
const goToHomePage = () => {
  router.push('/');
};

// 监听路由参数变化
watch(() => route.query, () => {
  getSearchParams();
  currentPage.value = 1;
  searchHomestays();
}, { deep: true });

// 组件挂载时初始化
onMounted(() => {
  getSearchParams();
  searchHomestays();
  fetchCategories();
  fetchCategoriesReing();
});
</script>

<style scoped>
.search-container {
  padding: 2rem 0;
  max-width: 1200px;
  margin: 0 auto;
}

/* 头部样式 */
.search-hero {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 3rem 2rem;
  margin-bottom: 2rem;
  text-align: center;
  color: white;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.search-title {
  font-size: 2.2rem;
  font-weight: 700;
  margin-bottom: 1.5rem;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-bar-wrapper {
  max-width: 700px;
  margin: 0 auto 1.5rem;
}

.search-input {
  height: 50px;
  border-radius: 25px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.search-info {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 0.8rem;
  font-size: 1rem;
}

.info-label {
  color: rgba(255, 255, 255, 0.8);
}

.search-tag {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  padding: 5px 15px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

/* 筛选区域样式 */
.filter-section {
  background-color: white;
  border-radius: 10px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.filter-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 1.2rem;
  color: #333;
}

.filter-item {
  margin-bottom: 0.5rem;
}

.filter-label {
  display: block;
  margin-bottom: 8px;
  font-size: 0.9rem;
  color: #606266;
}

.filter-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 1.7rem;
  gap: 10px;
}

.filter-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 结果区域样式 */
.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.results-title {
  font-size: 1.5rem;
  margin: 0;
  color: #333;
}

.search-results {
  min-height: 300px;
}

.homestay-card {
  margin-bottom: 24px;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 10px;
  overflow: hidden;
  border: none;
}

.homestay-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.homestay-image {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.homestay-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.homestay-card:hover .homestay-image img {
  transform: scale(1.05);
}

.homestay-price {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 6px 12px;
  border-radius: 20px;
  font-weight: bold;
  font-size: 1.1rem;
}

.price-unit {
  font-size: 0.8rem;
  font-weight: normal;
}

.homestay-info {
  padding: 15px;
  position: relative;
}

.homestay-type-badge {
  position: absolute;
  top: -12px;
  left: 15px;
  background-color: #409EFF;
  color: white;
  font-size: 0.8rem;
  padding: 3px 10px;
  border-radius: 12px;
}

.homestay-name {
  margin: 10px 0;
  font-size: 1.1rem;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.homestay-area {
  color: #666;
  margin-bottom: 10px;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 5px;
}

.homestay-rating {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.review-count {
  font-size: 0.8rem;
  color: #909399;
}

.pagination-section {
  text-align: center;
  margin-top: 2.5rem;
  padding-top: 1.5rem;
  border-top: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .search-container {
    padding: 1rem;
  }
  
  .search-hero {
    padding: 2rem 1rem;
  }
  
  .search-title {
    font-size: 1.8rem;
  }
  
  .filter-buttons {
    justify-content: center;
    margin-top: 1rem;
  }
  
  .results-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
}
</style> 